package com.park.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.park.bean.Manager;
import com.park.common.CommonResult;
import com.park.dao.IManagerDao;
import com.park.service.impl.ManagerServiceImpl;
import com.park.util.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.List;

@Component
public class ChangePassInterceptor implements HandlerInterceptor {
    @Autowired
    IManagerDao dao;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        List<Manager> list=dao.getManagerByUsername(username);
        if(list.size()==1){
            Manager manager_data=list.get(0);
            boolean bool= password.equals(ManagerServiceImpl.INITIAL_PASS);
            if(bool&&manager_data.getInitial()==0){
                System.out.println("触发了拦截器");
                //要回应的数据
                CommonResult result=CommonResult.fail(400,"Password has not been changed yet");
                //将数据解析成json
                String json= JSON.toJSONString(result);
                //将数据回应
                response.getWriter().write(json);
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
